'use client';

import { useMutation, useQuery } from '@tanstack/react-query';
import {
  applyOauthClientApi,
  createOauthClient,
  deleteOauthClient,
  queryOauthClientApis,
  queryOauthClientsByUser,
  queryOauthClientSecretById,
  updateOauthClientById,
  updateOauthClientSecretById,
} from '@/services/api';
import type { IDifference, IOauthClient, IOauthClientApi } from '@/interfaces';
import {
  type ChangeEvent,
  type Dispatch,
  type FormEvent,
  type SetStateAction,
  useContext,
  useEffect,
  useRef,
  useState,
} from 'react';
import useToast from '@/hooks/useToast';
import diff from 'microdiff';
import Link from 'next/link';
import { OAUTH_CLIENT_REVIEW_STATE_KEY } from '@/lib/constant';
import Image from 'next/image';
import { formatDate, getDiffData } from '@/lib/tool';
import type { IOauthClientPageContext } from '@/contexts/oauth-client';
import { OauthClientPageContext } from '@/contexts/oauth-client';
import Spinner from '@/app/[locale]/component/spinner/spinner';

export default function OauthClientPage({
  source,
  translatedFields,
}: IOauthClientPageContext) {
  const [isOpen, setIsOpen] = useState(false);
  const { show } = useToast();

  function onClickCreateClient() {
    setIsOpen(!isOpen);
  }

  function onClickViewDoc() {
    show({
      type: 'INFO',
      message: translatedFields.accessDocNotExist,
    });
  }

  return (
    <OauthClientPageContext.Provider value={{ source, translatedFields }}>
      <div className="col px-2 py-4">
        <div className="card border-0">
          <div className="card-body p-2 py-4 vstack gap-4">
            <div className="d-flex justify-content-between align-items-center">
              <div className="">
                <span>{translatedFields.authClient}</span>
                {source.path.clientConfig?.doc ? (
                  <span>
                    （
                    <Link
                      href={source.path.clientConfig.doc}
                      className="text-decoration-none text-decoration-underline-hover text-secondary"
                    >
                      {translatedFields.viewAccessDoc}
                    </Link>
                    ）
                  </span>
                ) : (
                  <span>
                    （
                    <a
                      onClick={onClickViewDoc}
                      className="text-decoration-none text-decoration-underline-hover text-secondary cursor-pointer"
                    >
                      {translatedFields.viewAccessDoc}
                    </a>
                    ）
                  </span>
                )}
              </div>
              <div className="hstack gap-4">
                {isOpen ? (
                  <button
                    onClick={onClickCreateClient}
                    type="button"
                    className="btn btn-light"
                  >
                    <i className="bi bi-x-lg me-2"></i>
                    {translatedFields.closeCreate}
                  </button>
                ) : (
                  <button
                    onClick={onClickCreateClient}
                    type="button"
                    className="btn btn-primary"
                  >
                    <i className="bi bi-plus-lg me-2"></i>
                    {translatedFields.createApp}
                  </button>
                )}
              </div>
            </div>

            {isOpen ? (
              <CreateClient setIsOpen={setIsOpen} />
            ) : (
              <Clients setIsOpen={setIsOpen} />
            )}
          </div>
        </div>
      </div>
    </OauthClientPageContext.Provider>
  );
}

const CreateClient = ({
  setIsOpen,
}: {
  setIsOpen: Dispatch<SetStateAction<boolean>>;
}) => {
  const { translatedFields } = useContext(OauthClientPageContext)!;
  const [form, setForm] = useState({
    name: '',
    website: '',
    callback: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const { show } = useToast();
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const createOauthClientMutation = useMutation(createOauthClient);

  useEffect(() => {
    const diffData = diff(
      {
        name: '',
        website: '',
        callback: '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form]);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const data = getDiffData(differenceData) as any;
      await createOauthClientMutation.mutateAsync({
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.saveComplete,
      });
    } catch (e) {
      createOauthClientMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setForm({
        name: '',
        website: '',
        callback: '',
      });
      setDifferenceData([]);
      setIsOpen(false);
    }
  }

  function onChange(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value.trim() });
  }

  function checkForm() {
    const { name, website, callback } = form;
    if (!name) {
      throw translatedFields.enterAppName;
    }

    if (!website) {
      throw translatedFields.enterAppSite;
    }

    if (!callback) {
      throw translatedFields.enterAppCallback;
    }
  }

  return (
    <div className="card">
      <div className="card-body">
        <form className="vstack gap-4" onSubmit={onSubmit}>
          <div className="">
            <label className="form-label">{translatedFields.appName}</label>
            <input
              name="name"
              value={form.name}
              onChange={onChange}
              type="text"
              className="form-control"
              placeholder={translatedFields.inputAppName}
            />
          </div>

          <div className="">
            <label className="form-label">{translatedFields.appSite}</label>
            <input
              name="website"
              value={form.website}
              onChange={onChange}
              type="url"
              className="form-control"
              placeholder={translatedFields.enterAppSite}
            />
            <div className="form-text">
              {translatedFields.siteOnlySupportHttpHttps}
            </div>
          </div>

          <div className="">
            <label className="form-label">{translatedFields.appCallback}</label>
            <input
              name="callback"
              value={form.callback}
              onChange={onChange}
              type="url"
              className="form-control"
              placeholder={translatedFields.enterAppCallback}
            />
            <div className="form-text">
              {translatedFields.callbackOnlySupportHttpHttps}
            </div>
          </div>

          <div>
            <div className="form-text text-secondary ">
              <i className="bi bi-info-circle me-2"></i>
              <ol>
                <li>{translatedFields.appInReview}</li>
                <li>{translatedFields.callbackChangeNeedReview}</li>
                <li>{translatedFields.defaultOpenAuthAccess}</li>
              </ol>
            </div>
          </div>

          <div className="text-center mt-4 mb-3">
            <button
              type="submit"
              disabled={createOauthClientMutation.isLoading || isDisabledSave}
              className="btn btn-success col col-lg-2 my-4"
            >
              {createOauthClientMutation.isLoading && <Spinner classs="me-2" />}
              {translatedFields.saveApp}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

const Clients = ({
  setIsOpen,
}: {
  setIsOpen: Dispatch<SetStateAction<boolean>>;
}) => {
  const { source, translatedFields } = useContext(OauthClientPageContext)!;
  const [currentId, setCurrentId] = useState<number>();
  const [currentItem, setCurrentItem] = useState<IOauthClient>();
  const [currentItem2, setCurrentItem2] = useState<IOauthClient>();
  const [isOpenAppSecret, setIsOpenAppSecret] = useState(false);
  const [isOpenUpdate, setIsOpenUpdate] = useState(false);
  const [isOpenInterface, setIsOpenInterface] = useState(false);
  const nameInputRef = useRef<HTMLInputElement>(null);
  const logoInputRef = useRef<HTMLTextAreaElement>(null);
  const overviewInputRef = useRef<HTMLTextAreaElement>(null);
  const websiteInputRef = useRef<HTMLTextAreaElement>(null);
  const callbackInputRef = useRef<HTMLTextAreaElement>(null);
  const { show } = useToast();

  const queryOauthClientsByUserQuery = useQuery(
    ['/oauth', '/clients', '/user'],
    async () => {
      return (await queryOauthClientsByUser()) as IOauthClient[];
    },
    {
      initialData: source.clients,
    },
  );
  const queryOauthClientSecretByIdQuery = useQuery(
    ['/oauth', '/clients', currentId, '/secret'],
    async (context) => {
      return (await queryOauthClientSecretById({
        id: context.queryKey[2] + '',
      })) as string;
    },
    {
      enabled: isOpenAppSecret && !!currentId,
    },
  );
  const queryOauthClientApisQuery = useQuery(
    ['/oauth', '/clients', '/apis', { cid: currentItem2?.id }],
    async (context) => {
      return (await queryOauthClientApis({
        query: (context.queryKey[3] || {}) as {},
      })) as IOauthClientApi[];
    },
    {
      enabled: isOpenInterface && !!currentItem2,
    },
  );

  const updateOauthClientSecretByIdMutation = useMutation(
    updateOauthClientSecretById,
  );
  const updateOauthClientByIdMutation = useMutation(updateOauthClientById);
  const applyOauthClientApiMutation = useMutation(applyOauthClientApi);
  const deleteOauthClientMutation = useMutation(deleteOauthClient);

  async function onClickSecret(item: IOauthClient) {
    setCurrentId(item.id);
    setIsOpenAppSecret(!isOpenAppSecret);
  }

  async function onClickResetSecret(item: IOauthClient) {
    try {
      setCurrentId(item.id);

      await updateOauthClientSecretByIdMutation.mutateAsync({
        id: item.id,
      });

      if (isOpenAppSecret) {
        await queryOauthClientSecretByIdQuery.refetch({
          throwOnError: true,
        });
      } else {
        setTimeout(() => {
          show({
            type: 'PRIMARY',
            message: translatedFields.appSecretTip,
          });
        }, 2500);
      }

      show({
        type: 'SUCCESS',
        message: translatedFields.resetAppSecretComplete,
      });
    } catch (e) {
      updateOauthClientSecretByIdMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onClickUpdate(item: IOauthClient) {
    setCurrentItem(item);
    setIsOpenUpdate(!isOpenUpdate);
  }

  async function onClickSaveUpdate(item: IOauthClient) {
    try {
      if (!currentItem) {
        show({
          type: 'DANGER',
          message: translatedFields.failToGetAppInfo,
        });
        return;
      } else if (currentItem.id !== item.id) {
        show({
          type: 'DANGER',
          message: translatedFields.failToSaveInfo,
        });
        return;
      }

      const inputValue = getInputValue();

      if (!Object.values(inputValue).filter((value) => value).length) {
        show({
          type: 'INFO',
          message: translatedFields.saveAppInfoComplete,
        });
        cleanData();
        return;
      }

      if (
        inputValue.name === item.name &&
        inputValue.overview === (item.overview || '') &&
        inputValue.logo === (item.logo || '') &&
        inputValue.website === (item.website || '') &&
        inputValue.callback === item.callback
      ) {
        show({
          type: 'INFO',
          message: translatedFields.saveAppInfoComplete,
        });
        cleanData();
        return;
      }

      await updateOauthClientByIdMutation.mutateAsync({
        id: item.id,
        data: inputValue,
      });
      await queryOauthClientsByUserQuery.refetch({ throwOnError: true });
      cleanData();

      show({
        type: 'SUCCESS',
        message: translatedFields.saveAppInfoComplete,
      });
    } catch (e) {
      updateOauthClientByIdMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onClickInterface(item: IOauthClient) {
    setCurrentItem2(item);
    setIsOpenInterface(!isOpenInterface);
  }

  async function onClickOpenInterface(
    item: IOauthClient,
    apiItem: IOauthClientApi,
  ) {
    try {
      if (apiItem.reviewState === 'SUCCESSFUL') {
        show({
          type: 'PRIMARY',
          message: translatedFields.accessGranted,
        });
        return;
      }

      if (apiItem.reviewState === 'PENDING') {
        show({
          type: 'INFO',
          message: translatedFields.inReviewQueue,
        });
        return;
      }

      await applyOauthClientApiMutation.mutateAsync({
        id: item.id,
        data: {
          apiId: apiItem.id + '',
        },
      });
      await queryOauthClientApisQuery.refetch({ throwOnError: true });

      show({
        type: 'SUCCESS',
        message: translatedFields.submitApplyComplete,
      });
    } catch (e) {
      applyOauthClientApiMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  async function onClickRemove(item: IOauthClient) {
    try {
      setCurrentId(item.id);

      await deleteOauthClientMutation.mutateAsync({
        id: item.id,
      });
      await queryOauthClientsByUserQuery.refetch({ throwOnError: true });

      show({
        type: 'SUCCESS',
        message: translatedFields.deleteAppComplete,
      });
    } catch (e) {
      deleteOauthClientMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onClickApiItemName() {
    show({
      type: 'INFO',
      message: translatedFields.noDocAvailable,
    });
  }

  function onClickAppName(item: IOauthClient) {
    onClickUpdate(item);
  }

  function onClickAppOther(item: IOauthClient) {
    onClickInterface(item);
  }

  function getInputValue() {
    return {
      name: nameInputRef.current?.value.trim(),
      overview: overviewInputRef.current?.value.trim(),
      logo: logoInputRef.current?.value.trim(),
      website: websiteInputRef.current?.value.trim(),
      callback: callbackInputRef.current?.value.trim(),
    };
  }

  function cleanData() {
    setIsOpenUpdate(false);
    setCurrentItem(undefined);
  }

  function onClickCreateApp() {
    setIsOpen(true);
  }

  return (
    <div className="card border-0">
      <div className="card-body">
        <div className="table-responsive">
          <table className="table">
            <caption className="text-secondary small mt-4 text-end">
              <i className="bi bi-info-circle me-2"></i>
              <span>{translatedFields.haveIssues}&nbsp;</span>
              <Link
                className="text-decoration-none text-decoration-underline-hover text-secondary"
                href={source.path.user ? '/posts/new' : '/login'}
              >
                {translatedFields.tryPost}
              </Link>
            </caption>
            <thead>
              <tr>
                <th scope="col">{translatedFields.appID}</th>
                <th scope="col">{translatedFields.name}</th>
                <th scope="col">{translatedFields.status}</th>
                <th scope="col">{translatedFields.create}</th>
                <th scope="col" style={{ width: 500 }}>
                  {translatedFields.operate}
                </th>
              </tr>
            </thead>
            <tbody>
              {queryOauthClientsByUserQuery.data.map((item) => {
                return (
                  <tr key={item.id} className="align-middle">
                    {isOpenUpdate ? (
                      <td colSpan={4}>
                        <table className="table table-borderless">
                          <tbody>
                            <tr className="align-middle">
                              <th className="text-nowrap">
                                {translatedFields.appID}
                              </th>
                              <td className="text-nowrap">
                                <input
                                  disabled
                                  value={item.clientId}
                                  className="form-control"
                                  type="text"
                                  aria-label="clientId"
                                />
                              </td>
                            </tr>
                            <tr className="align-middle">
                              <th className="text-nowrap">
                                {translatedFields.name}
                              </th>
                              <td className="text-nowrap">
                                <input
                                  ref={nameInputRef}
                                  defaultValue={item.name}
                                  className="form-control"
                                  type="text"
                                  aria-label="name"
                                />
                              </td>
                            </tr>
                            <tr className="align-middle">
                              <th className="text-nowrap">
                                {translatedFields.overview}
                              </th>
                              <td className="text-nowrap">
                                <textarea
                                  ref={overviewInputRef}
                                  defaultValue={item.overview || ''}
                                  className="form-control"
                                  rows={1}
                                  aria-label="overview"
                                />
                              </td>
                            </tr>
                            <tr className="align-middle">
                              <th className="text-nowrap">
                                {translatedFields.iconUrl}
                              </th>
                              <td className="text-nowrap">
                                <textarea
                                  ref={logoInputRef}
                                  defaultValue={item.logo || ''}
                                  className="form-control"
                                  rows={1}
                                  aria-label="logo"
                                />
                              </td>
                            </tr>
                            <tr className="align-middle">
                              <th className="text-nowrap">
                                {translatedFields.siteUrl}
                              </th>
                              <td className="text-nowrap">
                                <textarea
                                  ref={websiteInputRef}
                                  defaultValue={item.website || ''}
                                  className="form-control"
                                  rows={1}
                                  aria-label="website"
                                />
                              </td>
                            </tr>
                            <tr className="align-middle">
                              <th className="text-nowrap">
                                {translatedFields.callbackAddress}
                              </th>
                              <td className="text-nowrap">
                                <textarea
                                  ref={callbackInputRef}
                                  defaultValue={item.callback}
                                  className="form-control"
                                  rows={1}
                                  aria-label="callback"
                                />
                                <div className="form-text text-secondary">
                                  <i className="bi bi-info-circle me-2"></i>
                                  {
                                    translatedFields.needReapprovalOnCallbackChange
                                  }
                                </div>
                              </td>
                            </tr>
                            <tr className="align-middle">
                              <th className="text-nowrap"></th>
                              <td className="text-nowrap text-center">
                                <button
                                  disabled={
                                    currentItem &&
                                    item.id === currentItem.id &&
                                    updateOauthClientByIdMutation.isLoading
                                  }
                                  onClick={onClickSaveUpdate.bind(this, item)}
                                  type="button"
                                  className="btn btn-primary"
                                >
                                  {currentItem &&
                                  item.id === currentItem.id &&
                                  updateOauthClientByIdMutation.isLoading ? (
                                    <span
                                      className="spinner-border spinner-border-sm me-2"
                                      role="status"
                                      aria-hidden="true"
                                    ></span>
                                  ) : (
                                    <i className="bi bi-save me-2"></i>
                                  )}
                                  {translatedFields.saveInfo}
                                </button>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                      </td>
                    ) : (
                      <>
                        {isOpenInterface ? (
                          <td colSpan={4}>
                            <table className="table table-borderless">
                              <thead className="table-light">
                                <tr>
                                  <th scope="col">
                                    {translatedFields.function}
                                  </th>
                                  <th scope="col">
                                    {translatedFields.interface}
                                  </th>
                                  <th scope="col">
                                    {translatedFields.dailyCallVolume}
                                    &nbsp;/&nbsp;
                                    {translatedFields.limit}
                                  </th>
                                  <th scope="col">{translatedFields.status}</th>
                                  <th scope="col" className="text-nowrap">
                                    {translatedFields.operate}
                                  </th>
                                </tr>
                              </thead>
                              <tbody>
                                {queryOauthClientApisQuery.data &&
                                  queryOauthClientApisQuery.data.map(
                                    (apiItem) => {
                                      return (
                                        <tr
                                          key={apiItem.id}
                                          className="align-middle"
                                        >
                                          <td className="text-nowrap">
                                            {apiItem.category}
                                          </td>
                                          <td className="text-nowrap">
                                            {apiItem.doc ? (
                                              <Link
                                                className="link-primary text-decoration-none text-decoration-underline-hover"
                                                href={apiItem.doc}
                                                target="_blank"
                                              >
                                                {apiItem.overview ||
                                                  apiItem.name}
                                              </Link>
                                            ) : (
                                              <span
                                                className="link-primary cursor-pointer text-decoration-underline-hover"
                                                onClick={onClickApiItemName}
                                              >
                                                {apiItem.overview ||
                                                  apiItem.name}
                                              </span>
                                            )}
                                          </td>
                                          <td className="text-nowrap text-secondary">
                                            <span>
                                              {apiItem.dailyCalls || 0}
                                            </span>
                                            <span>&nbsp;/&nbsp;</span>
                                            <span>
                                              {apiItem.upperLimit === 0
                                                ? translatedFields.noLimit
                                                : apiItem.upperLimit}
                                            </span>
                                          </td>
                                          <td className="text-nowrap">
                                            {apiItem.type === 'DEFAULT' ||
                                            apiItem.reviewState ===
                                              'SUCCESSFUL' ? (
                                              <i
                                                className="bi bi-patch-check-fill me-2 text-success fs-5"
                                                title={translatedFields.granted}
                                              ></i>
                                            ) : apiItem.reviewState ===
                                              'FAILED' ? (
                                              <i
                                                className="bi bi-patch-check-fill me-2 text-danger fs-5"
                                                title={
                                                  translatedFields.notPassed
                                                }
                                              ></i>
                                            ) : (
                                              <span>
                                                {translatedFields.notGranted}
                                              </span>
                                            )}
                                          </td>
                                          <td className="text-nowrap">
                                            {apiItem.type === 'REQUIRED' &&
                                              apiItem.reviewState !==
                                                'SUCCESSFUL' && (
                                                <button
                                                  disabled={
                                                    (currentItem2 &&
                                                      item.id ===
                                                        currentItem2.id &&
                                                      applyOauthClientApiMutation.isLoading) ||
                                                    apiItem.reviewState ===
                                                      'PENDING'
                                                  }
                                                  onClick={onClickOpenInterface.bind(
                                                    this,
                                                    item,
                                                    apiItem,
                                                  )}
                                                  type="button"
                                                  className="btn btn-light"
                                                >
                                                  {currentItem2 &&
                                                  item.id === currentItem2.id &&
                                                  applyOauthClientApiMutation.isLoading ? (
                                                    <span>
                                                      <span
                                                        className="spinner-border spinner-border-sm me-2"
                                                        role="status"
                                                        aria-hidden="true"
                                                      ></span>
                                                      <span>
                                                        {
                                                          translatedFields.applyAccess
                                                        }
                                                      </span>
                                                    </span>
                                                  ) : (
                                                    <>
                                                      {apiItem.reviewState ===
                                                      'PENDING' ? (
                                                        <span>
                                                          {
                                                            translatedFields.waitReview
                                                          }
                                                        </span>
                                                      ) : (
                                                        <span>
                                                          <i className="bi bi-patch-plus me-2"></i>
                                                          <span>
                                                            {
                                                              translatedFields.applyAccess
                                                            }
                                                          </span>
                                                        </span>
                                                      )}
                                                    </>
                                                  )}
                                                </button>
                                              )}
                                          </td>
                                        </tr>
                                      );
                                    },
                                  )}
                              </tbody>
                            </table>
                          </td>
                        ) : (
                          <>
                            <th
                              className="text-nowrap user-select-all"
                              scope="row"
                            >
                              {item.clientId}
                            </th>
                            <td
                              title={translatedFields.modifyAuthClient}
                              onClick={onClickAppName.bind(this, item)}
                              className="text-nowrap cursor-pointer"
                            >
                              {item.logo ? (
                                <Image
                                  className="object-fit-cover"
                                  src={item.logo}
                                  alt={item.name}
                                  title={item.name}
                                  width={32}
                                  height={32}
                                />
                              ) : (
                                <span>{item.name}</span>
                              )}
                            </td>
                            <td
                              title={translatedFields.viewInterfaceList}
                              className="text-nowrap cursor-pointer"
                              onClick={onClickAppOther.bind(this, item)}
                            >
                              {item.reviewState === 'SUCCESSFUL' ? (
                                <i
                                  className="bi bi-patch-check-fill me-2 text-success fs-5"
                                  title={translatedFields.passed}
                                ></i>
                              ) : item.reviewState === 'FAILED' ? (
                                <i
                                  className="bi bi-patch-check-fill me-2 text-danger fs-5"
                                  title={translatedFields.notPassed}
                                ></i>
                              ) : (
                                <span>
                                  {
                                    OAUTH_CLIENT_REVIEW_STATE_KEY[
                                      item.reviewState
                                    ]
                                  }
                                </span>
                              )}
                            </td>
                            <td
                              title={translatedFields.viewInterfaceList}
                              className="text-nowrap cursor-pointer"
                              onClick={onClickAppOther.bind(this, item)}
                            >
                              <time dateTime={item.createdOn}>
                                {formatDate(item.createdOn)}
                              </time>
                            </td>
                          </>
                        )}
                      </>
                    )}

                    <td className="vstack gap-4 text-nowrap">
                      <div className="hstack gap-3">
                        <button
                          onClick={onClickUpdate.bind(this, item)}
                          type="button"
                          className="btn btn-light"
                        >
                          <i className="bi bi-pencil-square me-2"></i>
                          {isOpenUpdate
                            ? translatedFields.cancel
                            : translatedFields.modify}
                        </button>

                        <button
                          disabled={
                            isOpenInterface &&
                            currentItem2 &&
                            queryOauthClientApisQuery.isLoading
                          }
                          onClick={onClickInterface.bind(this, item)}
                          type="button"
                          className="btn btn-light"
                        >
                          {isOpenInterface &&
                          currentItem2 &&
                          queryOauthClientApisQuery.isLoading ? (
                            <span
                              className="spinner-border spinner-border-sm me-2"
                              role="status"
                              aria-hidden="true"
                            ></span>
                          ) : (
                            <i className="bi bi-door-open me-2"></i>
                          )}
                          {currentItem2 &&
                          isOpenInterface &&
                          !queryOauthClientApisQuery.isLoading
                            ? translatedFields.cancel
                            : translatedFields.interface}
                        </button>

                        <button
                          disabled={
                            currentId === item.id &&
                            isOpenAppSecret &&
                            queryOauthClientSecretByIdQuery.isLoading
                          }
                          onClick={onClickSecret.bind(this, item)}
                          type="button"
                          className="btn btn-light"
                        >
                          {currentId === item.id &&
                          isOpenAppSecret &&
                          queryOauthClientSecretByIdQuery.data ? (
                            <span>
                              <i className="bi bi-shield-shaded me-2"></i>
                              {translatedFields.hide}
                            </span>
                          ) : (
                            <span>
                              {currentId === item.id &&
                              isOpenAppSecret &&
                              queryOauthClientSecretByIdQuery.isLoading ? (
                                <span
                                  className="spinner-border spinner-border-sm me-2"
                                  role="status"
                                  aria-hidden="true"
                                ></span>
                              ) : (
                                <i className="bi bi-shield me-2"></i>
                              )}
                              {translatedFields.secret}
                            </span>
                          )}
                        </button>

                        <button
                          disabled={
                            currentId === item.id &&
                            updateOauthClientSecretByIdMutation.isLoading
                          }
                          onClick={onClickResetSecret.bind(this, item)}
                          type="button"
                          className="btn btn-light"
                        >
                          {currentId === item.id &&
                          updateOauthClientSecretByIdMutation.isLoading ? (
                            <span
                              className="spinner-border spinner-border-sm me-2"
                              role="status"
                              aria-hidden="true"
                            ></span>
                          ) : (
                            <i className="bi bi-shield-lock me-2"></i>
                          )}
                          {translatedFields.resetSecret}
                        </button>

                        <button
                          disabled={
                            currentId === item.id &&
                            deleteOauthClientMutation.isLoading
                          }
                          onClick={onClickRemove.bind(this, item)}
                          type="button"
                          className="btn btn-light"
                        >
                          {currentId === item.id &&
                          deleteOauthClientMutation.isLoading ? (
                            <span
                              className="spinner-border spinner-border-sm me-2"
                              role="status"
                              aria-hidden="true"
                            ></span>
                          ) : (
                            <i className="bi bi-trash me-2"></i>
                          )}
                          {translatedFields.deleteApp}
                        </button>
                      </div>
                      <>
                        {isOpenAppSecret &&
                          queryOauthClientSecretByIdQuery.data && (
                            <div>
                              <p className="text-secondary user-select-all cursor-copy text-decoration-underline-hover">
                                {queryOauthClientSecretByIdQuery.data}
                              </p>
                              <div className="user-select-none form-text text-secondary">
                                <i className="bi bi-question-circle me-2 text-warning"></i>
                                {translatedFields.appSecret}
                              </div>
                            </div>
                          )}

                        {isOpenAppSecret &&
                          queryOauthClientSecretByIdQuery.error && (
                            <div>
                              <p className="text-danger">
                                {translatedFields.failToGetSecret}
                              </p>
                            </div>
                          )}
                      </>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {queryOauthClientsByUserQuery.data.length === 0 && (
          <div className="text-secondary text-center my-4">
            <span>{translatedFields.noAppAvailable}</span>（
            <span
              className="link-primary text-decoration-underline-hover cursor-pointer"
              onClick={onClickCreateApp}
            >
              {translatedFields.startCreateApp}
            </span>
            ）
          </div>
        )}
      </div>
    </div>
  );
};
